
$(document).ready(function () {
    //初始化头
    initNavbar();
    initPage();
    getPagedata();
});

/**
 * 初始页面
 */
function initPage(){
    //链接表单
    new bsEx.ItemForm({
        id: "MQform",
        renderto: '#MQform',
        items: [
            { type: 'text', name: 'MQIP', title: 'IP:' },
            { type: 'text', name: 'MQPort', title: '端口:',value:"61614" }
        ],
        readonly:['MQPort'],requireds:['MQIP','MQPort'],validate:true,
        colunb: 2, showlabel: true
    }).init();

    /*按钮绘制开始*/
    new bsEx.Button({id:"btn1",renderto:"#btn1",text:"链接",btntype:1});
    new bsEx.Button({id:"btn2",renderto:"#btn2",text:"断开",btntype:1});
    //new bsEx.Button({id:"btn3",renderto:"#btn3",text:"保存当前配置",btntype:1});
    btn1 = bsEx.ui['btn1'];
    btn2 = bsEx.ui['btn2'];
    btn3 = bsEx.ui['btn3'];
    /*按钮绘制结束*/

    //推送 和 监听 的主题按钮
    new bsEx.Button({id:"btnsubadd",renderto:"#btnsubadd",text:"添加主题",btntype:1,onclick:function(){
        bsEx.Alert('提示', '没做那', 1);
    }});
    new bsEx.Button({id:"btnpubadd",renderto:"#btnpubadd",text:"添加主题",btntype:1,onclick:function(){
        bsEx.Alert('提示', '没做那', 1);
    }});
    btnsubadd = bsEx.ui['btnsubadd'];
    btnpubadd = bsEx.ui['btnpubadd'];



    //监听表单
    new bsEx.ItemForm({
        id: "subform",
        renderto: '#subform',
        items: [
            { type: 'text', name: 'subname', title: '监听主题:' },
            { type: 'textarea', name: 'submsg', title: '接收信息:', height: '250px' }
        ],
        readonly:['submsg'],autoLayout:['2,10'],
        colunb: 1, showlabel: true
    }).init();

    //发送的表单
    new bsEx.ItemForm({
        id: "pubform",
        renderto: '#pubform',
        items: [
            { type: 'text', name: 'pubname', title: '主题:' },
            { type: 'text', name: 'pubtitle', title: '发送标题:' },
            { type: 'text', name: 'btntitles' },
            { type: 'textarea', name: 'pubmsg', title: '发送信息:', height: '250px' }
        ],
        readonly:[''],autoLayout:['2,10'],
        colunb: 1, showlabel: true
    }).init();

    //增加按钮
    pubname = $('#pubname');
    //btnpub = pubname.addbutton("发送");
    subname = $('#subname');
    btnsub = subname.addbutton("开始监听");
    pubmsg = $('#pubmsg');
    btnformat = pubmsg.addbutton("整理");
    pubtitle = $('#pubtitle');
    btnaddtitle = pubtitle.addbutton("新增");

    //标题按钮的行
    btntitles = $('#btntitles').parent();
    btntitles.html("");
    btntitles.append('<div id="btntitles"  data-toggle="buttons" class="btn-group"></div>');
    btngroup = new bsEx.BtnGroup({
        renderto:"#btntitles",
        btns:[{id:'btnpub',text:'发送'}]
    });

    //新增标题
    addtitle = function(title){
        //绘制标题的按钮
        var btn;
        if(bsEx.isObj(title)){
            btn = btngroup.appendbtn(title);
        }
        else{
            btn = btngroup.appendbtn({id:title+bsEx.getId(),text:'<input type="radio" name="table"> '+title});
        }
        pubtitle.val('');
        pubmsg.val('');
        //点击标题时把上次的值赋上
        btn.on('click',function(){
            pubmsg.title = btn;
            if(btn.msg){
                pubmsg.val(btn.msg);
            }else{
                pubmsg.val('');
            }
        })
        btn.on('dblclick',function(){
            var prevbtn = $(btn.renderto).prev();
            //清除该按钮
            btngroup.removebtn(btn);
            //找到上一个按钮，不是 btnpub 的 执行点击
            var pid = prevbtn.attr('bsexid');
            if(pid && pid!='btnpub'){
                bsEx.ui[pid].click();
            }else{
                //找不到 执行pubmsg.val('');
                pubmsg.val('');
            }
        })
        //新按钮执行一次点击
        $(btn.renderto).click();
    }
    //新增标题事件
    btnaddtitle.on("click",function(){
        //如果标题不为空
        var v = pubtitle.val();
        if(v!=""){
            addtitle(v);
        }
    });

    //开始监听
    submsg = $('#submsg');
    submsg.append = function () {
        arguments[0] = arguments[0] +' \r\n  ';
        ($.fn.append).apply(this,arguments);
    }
    //开始监听事件
    btnsub.on('click',function(){
        var v = subname.val();
        if(_MQC.cliented){
            if(btnsub.text == "开始监听" && v!=""){
                btnsub.settext('停止监听');
                subname.attr('readonly','readonly');
                //注册监听
                _MQC.subscribe(v);
                //该主题的事件
                _MQC.on(v,function(msg){
                    //msg = js_beautify(JSON.stringify(msg));
                    submsg.append('');
                    submsg.append(global.Fn.formatDate(new Date().getTime().toString(),'yyyy-MM-dd hh:mm:ss'));
                    submsg.append(JSON.stringify(msg));
                    var scrollTop = submsg[0].scrollHeight;
                    submsg.scrollTop(scrollTop);
                });
            }else{
                //注销事件
                _MQC.off(v);
                btnsub.settext('开始监听');
                subname.removeAttr('readonly');
            }
        }
    })

    //发送事件
    bsEx.ui['btnpub'].on('click',function(t){
        if(_MQC.cliented){
            t.loading('<i class="fa fa-circle-o-notch fa-spin"></i>正在发送...');
            var name = pubname.val();
            var msg = pubmsg.val();
            pubmsg.title.msg = msg;
            var _msg = JSON.stringify(JSON.parse(msg));
            _MQC.publish(name,_msg);
            t.reset();
        }
    })
    
    //整理事件
    btnformat.on('click',function(){
        var msg = pubmsg.val();
        pubmsg.val(js_beautify(msg));
    })

    setInterval(function(){
        savePage();
    },30);
}

/**
 * 链接事件
 */
function btn1_onclick(){
    if(bsEx.ui["MQform"].valid()){
        var data = bsEx.ui["MQform"].getFormData();
        var config = {MQIP:data.MQIP,MQPort:parseInt(data.MQPort)};
        _MQC = new MQC(config);
        //开始链接
        _MQC.on("beforclient",function(msg){
            btn2.setdisabled(true);//断开按钮失效
            console.log("开始连接"+_MQC.config.MQIP);
            btn1.loading('<i class="fa fa-circle-o-notch fa-spin"></i>正在连接...');
        })
        //链接成功
        _MQC.on("cliented",function(msg){
            btn2.setdisabled(false);//断开按钮有效
            //btn1.reset();//链接按钮重置
            btn1.setdisabled(true);//链接按钮失效
            btn1.settext("链接成功");
        })
        //链接失败
        _MQC.on("clientFail",function(msg){
            //断开
            btn2_onclick();
        })
        //链接失败
        _MQC.on("clientlost",function(msg){
            //断开
            btn2_onclick();
        })
        //开始链接
        _MQC.client();
    };
}
/**
 * 断开
 */
function btn2_onclick(){
    if(btnsub.text == "停止监听"){
        btnsub.click();
    }
    _MQC = {};
    btn1.reset();//链接按钮重置
    btn2.reset();//断开按钮重置
    btn1.setdisabled(false);//链接按钮有效
    btn2.setdisabled(false);//断开按钮有效
}

/**
 * 初始化头
 */
function initNavbar(){
    new bsEx.Navbar({
        renderto:"#topnavbar",
        title:"ActiveMQTest",
        meuns:[],
        cls:"",
        right:[
            {text:"联系我",children:[
                {text:"@北京-没想好",istitle:true},
                {text:"<a href='tencent://message/?uin=935732994&Site=''&Menu=yes' target='_black'>QQ</a>"}
            ]}
        ]
    });
}

/**
 * 页面存储数据
 * @param {string} key 名称
 * @param {string} val 值
 */
function setData(key,val){
    var curTime=new Date().getTime();
    localStorage.setItem(key,JSON.stringify(val))
}


/**
 * 获取页面数据
 * @param {string} key 名称
 */
function getData(key){
    var data=localStorage.getItem(key);
    return data;
}

/**
 * 得到页面数据
 */
function getPagedata(){
    var pagedata = getData('pagedata');
    if(pagedata){
        pagedata = eval('('+pagedata+')');
        for(var i in pagedata){
            var data = pagedata[i];
            if(data && bsEx.ui[i] && bsEx.ui[i].setFormData){
                data = eval('('+data+')');
                if(i == "MQform"){
                    bsEx.ui[i].setFormData(data);
                }
                if(i == "subform"){
                    subname.val(data['subname']);
                }
                if(i == "pubform"){
                    pubname.val(data['pubname']);
                }
            }
        }
    }
    var btngroup = getData('btngroup');
    var btngroupMsg = getData('btngroupMsg');
    if(btngroup && btngroupMsg){
        btngroup = eval('('+btngroup+')');
        btngroupMsg = eval('('+btngroupMsg+')');
        btngroup.forEach(function(item){
            if(item.id!="btnpub"){
                item.msg = btngroupMsg[item.id];
                addtitle(item);
            }
        })
    }

}

/**
 * 保存页面数据z
 */
function savePage(){
    var pagedata = {};
    $.each($('form'),function(index,item){
        var id = $(item).attr('bsexid');
        if(id && bsEx.ui[id] && bsEx.ui[id].getFormData){
            var data  = bsEx.ui[id].getFormData();
            pagedata[id] = JSON.stringify(data);
        }
    })
    setData('pagedata',pagedata);
    setData('btngroup',btngroup.btns);
    var btngroupMsg = {};
    btngroup.btns.forEach(function(item){
        btngroupMsg[item.id] =  bsEx.ui[item.id].msg;
    })
    setData('btngroupMsg',btngroupMsg);
    
}